﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

using HtmlAgilityPack;

namespace TorBrowserUpdater
{
    class TBBVersionRetriever
    {

        public static Properties.Settings DefaultSettings
        {
            get
            {
                return Properties.Settings.Default;
            }
        }

        public static string getReleaseVer(TBBUpdater.PlatformType platform)
        {
            //It's the same release version for every platform (obviously), so we can retrieve the version in versions.mk.
            const string releaseVerPattern = "RELEASE_VER=([^\n]+)";
            string versionsContent;
            Match match;
            
            versionsContent = Tools.DownloadString(DefaultSettings.TBBVersionsMakefileUri);
            match = Regex.Match(versionsContent, releaseVerPattern);

            if (!match.Success)
            {
                throw new TBBUpdaterException("The ReleaseVer info could not be found.");
            }

            return match.Groups[1].Value.Trim();            
        }

        public static string getBuildNum(TBBUpdater.PlatformType platform)
        {
            //It's the same release version for every platform (obviously), so we can retrieve the version in versions.mk.
            const string releaseVerPattern = "BUILD_NUM=([^\n]+)";
            string makeFileContent;
            Match match;
            string platformMakefileUrl;

            switch (platform)
            {
                case TBBUpdater.PlatformType.Windows:
                    platformMakefileUrl = DefaultSettings.TBBWindowsMakefileUri;
                    break;
                case TBBUpdater.PlatformType.Linux:
                    platformMakefileUrl = DefaultSettings.TBBLinuxMakefileUri;
                    break;
                case TBBUpdater.PlatformType.MaxOSX:
                    platformMakefileUrl = DefaultSettings.TBBOsxMakefileUri;
                    break;
                default:
                    throw new TBBUpdaterException(String.Format("The platform {0} is not a valid platform.",
                                                                platform));
            }

            makeFileContent = Tools.DownloadString(platformMakefileUrl);
            match = Regex.Match(makeFileContent, releaseVerPattern);

            if (!match.Success)
            {
                throw new TBBUpdaterException("The BuildNum info could not be found.");
            }

            return match.Groups[1].Value.Trim();            
        }

    }
}
